package com.hp.bon.sgw.wh.channel.handler;

import java.io.IOException;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.google.gson.Gson;
import com.hp.bon.sgw.Constants;
import com.hp.bon.sgw.Constants.MessageType;
import com.hp.bon.sgw.bean.XmlMessage;
import com.hp.bon.sgw.core.BuzProcessorManager;
import com.hp.bon.sgw.core.CallParam;
import com.hp.bon.sgw.core.channel.SoapChannel;
import com.hp.bon.sgw.core.channel.handler.IAsynCallHandler;
import com.hp.bon.sgw.domain.MessageDetail;
import com.hp.bon.sgw.threads.MessageDetailCacheManager;
import com.hp.bon.sgw.threads.TaskManager;
import com.hp.ocs.diameter.message.Message;

public class QryBalanceModifyLogHandle implements IAsynCallHandler {
	
	private static final Logger _log = LoggerFactory.getLogger(QryBalanceModifyLogHandle.class);
	private PrintStream printStream;
	private JSONObject jsonContent;
	
	public QryBalanceModifyLogHandle(PrintStream printStream, JSONObject jsonContent) {
		this.printStream = printStream;
		this.jsonContent = jsonContent;
	}

	@Override
	public int getProtocolType() {
		return 0;
	}

	@Override
	public void onCallResult(CallParam callParam) {
		XmlMessage ack = null;
		Object response = null;
		if (callParam.getResponse() != null) {
			response = callParam.getResponse();
		} else if (callParam.getRecvResponse() != null) {
			response = callParam.getRecvResponse();
		}
		if (response == null) {
			int _retcodeTmp = callParam.getRetCode() == 3002 ? 11202 : callParam.getRetCode();
			ack = SoapChannel.createERRAnwser(callParam.getSessionId(), _retcodeTmp, callParam.getResultMsg());
			callParam.setServiceResultCode(_retcodeTmp);// 11203
		} else {
			if (response instanceof Message) {// CCA -> XML
				ack = BuzProcessorManager.getInstance().convertMessageToAck(callParam);
			} else if (response instanceof XmlMessage) {
				ack = (XmlMessage) response;
			} else {
				_log.warn("unknown response type:" + callParam.getResponse().getClass().getName());
			}
		}
		try {
			String respXML = convertResponseString(ack, callParam.getServiceResultCode());
			byte[] resp = respXML.getBytes("UTF-8");
			ack.setLength(resp.length);
			ack.setMsgTime(System.currentTimeMillis());
			printStream.write(resp);
			printStream.close();
			callParam.setResponse(ack);
			if (callParam.getRetCode() == Constants.ResultCode.SUCCESS) {// 成功的消息，请求应答入库
				MessageDetail detail = new MessageDetail();
				detail.setBusinessCallId(callParam.getBussinessCallId());
				detail.setSessionId(callParam.getSessionId());
				detail.setServiceContextId(callParam.getServiceContextId());
				detail.setMessageType(MessageType.WSA);
				detail.setDetails(ack.getDATA());
				detail.setMsgTime(new Date(ack.getMsgTime()));
				detail.setOpType("send");
				detail.setHostId(callParam.getUserName());
				MessageDetailCacheManager.getInstance().add(detail);
			}
			TaskManager.taskProcess(callParam);
			_log.info("http response(returnBalance) " + respXML);
		} catch (UnsupportedEncodingException e) {
			_log.info("convertResponseString UnsupportedEncodingException error,msg=" + e.getMessage());
		} catch (IOException e) {
			_log.info("convertResponseString IOException,msg=" + e.getMessage());
		}
	}

	
	
	/**
	 * 从Message中解析出需要的数据，并拼接成json字符串
	 * @param answer
	 * @param serviceResultCode
	 * @return
	 */
	private String convertResponseString(XmlMessage ack, int serviceResultCode) {
		_log.info("QryBalanceModifyLogHandle serviceResultCode = {}", serviceResultCode);
		String response = "";
		Map<String, Object> data = new HashMap<String, Object>();
		if (serviceResultCode == 0) {
			response = ack.getDATA();
//			try{
//				response = response.substring(response.indexOf("{"), response.indexOf("</result>"));
//			}catch(Exception e){
//				_log.error("解析下游webservice接口返回信息出错，返回信息中未发现<result>{}</result>");
//				//response = "";
//			}
			JSONObject jsonResponse = JSONObject.parseObject(response);
			if(jsonResponse == null) {
				data.put("resultCode", "-1");
				data.put("resultMsg", "record is null");
			}else if("0".equals(jsonResponse.get("resultCode"))){
				data.putAll(jsonResponse);
				data.put("resultCode", "0");
				data.put("resultMsg", "SUCCESS");
			}else{
				data.put("resultCode", jsonResponse.get("resultCode"));
				data.put("resultMsg", jsonResponse.get("resultMsg"));
			}
			_log.info("QryBalanceModifyLogHandle convertResponseString = {}", response);
		} else {
			data.put("resultCode", "-1");
			data.put("resultMsg", "fail");
			_log.info("QryBalanceModifyLogHandle convertResponseString = {}", response);
		}
		Gson gson = new Gson();
		response = gson.toJson(data);
		return response;
	}
}
